<template>
  <el-card>
    <div class="text-center">
      <el-input
        class="cus-inp"
        :prefix-icon="Search"
        v-model="state.keyWord"
        placeholder="搜索音乐、MV、歌单"
        clearable
        @input="changeInput"
      />
    </div>
    <CommonSearchList :song-list="state.songList" />
    <el-button v-if="state.hasMore" type="success" link @click="loadMore" v-loading="state.isLoading">
      加载更多
    </el-button>
  </el-card>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import { Search } from '@icon-park/vue-next'
import { useRoute } from 'vue-router'
import { debounce } from 'lodash-es'
import { commonSearch } from '@/api/search'
import CommonSearchList from '@/components/list/common-search/CommonSearchList.vue'
import type { Song } from '@/types/song'

const state = reactive({
  keyWord: '',
  songList: [] as Array<Song>, //列表
  hasMore: false,
  limit: 20,
  offset: 0,
  isLoading: false,
})
const onSearch = async () => {
  if (!state.keyWord.length) {
    state.songList = []
    state.hasMore = false
    return
  }
  state.isLoading = true
  const { data } = await commonSearch(state.keyWord, state.limit, state.offset)
  state.isLoading = false
  if (data.code !== 200) return ElMessage.error('获取失败')
  state.songList = [...state.songList, ...data.result.songs]
  state.hasMore = data.result.hasMore
}

const loadMore = () => {
  state.offset += 1
  onSearch()
}

const changeInput = debounce(onSearch, 1000)
</script>

<style lang="less" scoped>
.el-card {
  @apply shadow;
  border: none;
  .cus-inp {
    :deep(.el-input__wrapper) {
      border-radius: 50px;
    }
    @apply w-60;
  }
  .el-button {
    @apply m-auto block;
  }
}
</style>
